<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <div class="logo-text">双创实验室</div>
      </div>
      <div class="menu-items">
        <div class="menu-item" @click="createNewChat">
          <span class="icon">
            <el-icon><Plus /></el-icon>
          </span>
          <span class="text">新建会话</span>
          <span class="shortcut">
            <span class="key">Ctrl</span>
            <span class="key">K</span>
          </span>
        </div>
        <div class="menu-item">
          <span class="icon">
            <el-icon><Clock /></el-icon>
          </span>
          <span class="text">历史会话</span>
        </div>
        <div class="history-list">
          <div 
            v-for="chat in chatHistory" 
            :key="chat.chatId"
            class="history-item"
            :class="{ active: currentChatId === chat.chatId }"
            @click="selectChat(chat.chatId)"
          >
            <span class="chat-title">{{ chat.title || '无标题' }}</span>
            <span class="chat-time">{{ formatTime(chat.createTime) }}</span>
          </div>
          <div v-if="chatHistory.length === 0" class="no-history">
            暂无历史会话
          </div>
        </div>
      </div>
      <div class="delete-session" v-if="currentChatId">
        <div class="operate delete" @click="deleteCurrentChat">
          <span class="icon">
            <el-icon><Delete /></el-icon>
          </span>
          <span class="text">删除</span>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="chat-header">
        <h1>欢迎来到 Lab-OJ</h1>
        <div v-if="currentChatId" class="current-chat-info">
          当前会话: {{ currentChatId }}
        </div>
      </div>
      <div class="chat-messages" ref="chatMessagesRef">
        <div v-if="messages.length === 0" class="welcome-message">
          <p>你好！我是Lab-OJ智能助手，有什么可以帮助你的吗？</p>
        </div>
        <div 
          v-for="message in messages" 
          :key="message.id"
          class="message"
          :class="{ 'user-message': message.role === 'user', 'bot-message': message.role === 'bot' }"
        >
          <div class="message-content" v-html="formatMessage(message.content)"></div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
        <div v-if="isLoading" class="message bot-message">
          <div class="message-content">
            <el-icon class="is-loading"><Loading /></el-icon>
            正在思考中...
          </div>
        </div>
        <div class="bottom-line"></div>
      </div>
      <div class="chat-input-container">
        <div class="input-wrapper">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="输入你的问题，帮你深度解答"
            @keydown.enter.prevent="handleSendMessage"
            :disabled="isLoading"
            ref="inputRef"
          />
          <div class="input-buttons">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :icon="Position" 
                @click="handleSendMessage"
                :loading="isLoading"
                :disabled="!userInput.trim()"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Clock, Delete, Position, Loading } from '@element-plus/icons-vue'
import { 
  getChatIdsService, 
  getChatHistoryService, 
  deleteChatService, 
  streamChatService 
} from '@/apis/bot'

// 响应式数据
const userInput = ref('')
const isLoading = ref(false)
const currentChatId = ref('')
const messages = ref([])
const chatHistory = ref([])
const chatMessagesRef = ref()
const inputRef = ref()

// 生成会话ID
function generateChatId() {
  return 'chat-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9)
}

// 创建新聊天
const createNewChat = async () => {
  // 不立即创建chatId，而是在发送第一条消息时创建
  currentChatId.value = ''
  messages.value = []
  userInput.value = ''
  
  console.log('准备新建会话')
}

// 选择聊天
const selectChat = async (chatId) => {
  console.log('选择聊天:', chatId)
  currentChatId.value = chatId
  await loadChatMessages(chatId)
}

// 加载聊天历史列表
const loadChatHistory = async () => {
  try {
    console.log('开始加载聊天历史...')
    const result = await getChatIdsService()
    console.log('聊天历史API响应:', result)
    
    // 现在result.data就是ChatInfo数组
    chatHistory.value = result.data || []
    console.log('历史记录:', chatHistory.value)
    
    // 如果历史记录为空，显示提示
    if (chatHistory.value.length === 0) {
      console.log('当前没有历史会话记录')
    }
    
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    chatHistory.value = []
    ElMessage.error('加载聊天历史失败: ' + error.message)
  }
}

// 加载指定聊天的消息
const loadChatMessages = async (chatId) => {
  try {
    console.log('加载聊天消息，chatId:', chatId)
    const result = await getChatHistoryService(chatId)
    console.log('聊天消息API响应:', result)
    
    // 现在result.data就是MessageVO数组
    messages.value = result.data || []
    
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('加载聊天消息失败:', error)
    ElMessage.error('加载聊天消息失败: ' + error.message)
    messages.value = []
  }
}

// 删除当前聊天
const deleteCurrentChat = async () => {
  if (!currentChatId.value) return
  
  try {
    await ElMessageBox.confirm('确认删除此会话吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteChatService(currentChatId.value)
    ElMessage.success('删除成功')
    
    // 从历史记录中移除
    chatHistory.value = chatHistory.value.filter(chat => chat.chatId !== currentChatId.value)
    
    // 清空当前会话
    currentChatId.value = ''
    messages.value = []
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除聊天失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 发送消息
const handleSendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return
  
  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: userInput.value.trim(),
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const inputText = userInput.value.trim()
  userInput.value = ''
  
  await nextTick()
  scrollToBottom()
  
  isLoading.value = true
  
  try {
    // 如果没有当前聊天ID，创建一个新的
    if (!currentChatId.value) {
      currentChatId.value = generateChatId()
      console.log('创建新会话ID:', currentChatId.value)
    }
    
    // 调用流式聊天接口
    const response = await streamChatService(inputText, currentChatId.value)
    
    // 创建机器人消息
    const botMessage = {
      id: Date.now() + 1,
      role: 'bot',
      content: '',
      timestamp: new Date()
    }
    messages.value.push(botMessage)
    
    // 处理流式响应
    await handleStreamResponse(response, botMessage)
    
    // 发送消息后，重新加载聊天历史
    await loadChatHistory()
    
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
    
    // 移除用户消息
    messages.value = messages.value.filter(msg => msg.id !== userMessage.id)
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 处理流式响应
const handleStreamResponse = async (response, botMessage) => {
  try {
    console.log('开始处理流式响应:', response)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    
    while (true) {
      const { done, value } = await reader.read()
      if (done) {
        console.log('流式响应结束')
        break
      }
      
      const chunk = decoder.decode(value, { stream: true })
      console.log('收到数据块:', chunk)
      
      // 直接添加到消息内容
      botMessage.content += chunk
      
      // 强制触发响应式更新
      messages.value = [...messages.value]
      
      // 等待DOM更新
      await nextTick()
      scrollToBottom()
    }
    
  } catch (error) {
    console.error('处理流式响应失败:', error)
    botMessage.content = '抱歉，响应处理出现问题。'
  }
}

// 格式化消息内容（支持Markdown和数学公式）
const formatMessage = (content) => {
  // 简单的HTML转义
  return content
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br>')
    .replace(/\$\$(.*?)\$\$/g, '<div class="math-display">$$$1$$</div>')
    .replace(/\$(.*?)\$/g, '<span class="math-inline">$$$1$$</span>')
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
  }
}

// 监听消息变化，自动滚动
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 键盘快捷键
const handleKeyDown = (event) => {
  if (event.ctrlKey && event.key === 'k') {
    event.preventDefault()
    createNewChat()
  }
}

// 组件挂载
onMounted(async () => {
  console.log('Chat组件已挂载，开始加载历史记录...')
  await loadChatHistory()
  document.addEventListener('keydown', handleKeyDown)
})

// 组件卸载
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.logo {
  padding: 18px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
}

.menu-items {
  flex: 1;
  padding: 16px 0;
  overflow-y: auto;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background: #f5f5f5;
  }
  
  .icon {
    margin-right: 12px;
    color: #666;
  }
  
  .text {
    flex: 1;
    color: #333;
  }
  
  .shortcut {
    display: flex;
    gap: 4px;
    
    .key {
      padding: 2px 6px;
      background: #f0f0f0;
      border-radius: 4px;
      font-size: 12px;
      color: #666;
    }
  }
}

.history-list {
  margin-top: 8px;
}

.history-item {
  padding: 8px 16px;
  cursor: pointer;
  border-left: 3px solid transparent;
  transition: all 0.2s;
  
  &:hover {
    background: #f5f5f5;
  }
  
  &.active {
    background: #e3f2fd;
    border-left-color: #32c5ff;
  }
  
  .chat-title {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .chat-time {
    font-size: 12px;
    color: #999;
  }
}

.no-history {
  padding: 8px 16px;
  color: #999;
  font-size: 12px;
  text-align: center;
}

.delete-session {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.operate {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.2s;
  
  &:hover {
    background: #f5f5f5;
  }
  
  .icon {
    margin-right: 8px;
    color: #666;
  }
  
  .text {
    color: #333;
    font-size: 14px;
  }
  
  &.delete:hover {
    background: #ffebee;
    color: #f44336;
    
    .icon, .text {
      color: #f44336;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  
  h1 {
    margin: 0;
    font-size: 24px;
    color: #333;
    font-weight: 500;
  }
  
  .current-chat-info {
    margin-top: 8px;
    font-size: 14px;
    color: #666;
  }
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.welcome-message {
  text-align: center;
  color: #666;
  font-size: 16px;
  margin-top: 50px;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 80%;
  
  &.user-message {
    align-self: flex-end;
    
    .message-content {
      background: #32c5ff;
      color: #fff;
      border-radius: 18px 18px 4px 18px;
    }
  }
  
  &.bot-message {
    align-self: flex-start;
    
    .message-content {
      background: #f5f5f5;
      color: #333;
      border-radius: 18px 18px 18px 4px;
    }
  }
}

.message-content {
  padding: 12px 16px;
  line-height: 1.5;
  word-wrap: break-word;
  
  :deep(.math-display) {
    display: block;
    text-align: center;
    margin: 10px 0;
    padding: 10px;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  
  :deep(.math-inline) {
    background: rgba(0, 0, 0, 0.05);
    padding: 2px 4px;
    border-radius: 2px;
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.bottom-line {
  height: 1px;
  background: transparent;
}

.chat-input-container {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-buttons {
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  resize: none;
  
  &:focus {
    border-color: #32c5ff;
    box-shadow: 0 0 0 2px rgba(50, 197, 255, 0.1);
  }
}

:deep(.el-button--primary) {
  background-color: #32c5ff;
  border-color: #32c5ff;
  
  &:hover {
    background-color: #1bb3ff;
    border-color: #1bb3ff;
  }
}
</style>